import React from "react";
import LazyLoad from "@/components/lazyLoad";
import Layout from "@/layout/layout.tsx";
import {Navigate} from "react-router-dom";
import {staticRoutes} from "@/router";
import RouterGuard from "@/router/modules/RouterGuard.tsx";

const modules: Record<string, () => Promise<any>> = import.meta.glob("@/views/**/**.tsx");

export const getAllBreadcrumbList = (menuList: any, parent: any = [], result: { [key: string]: any } = {}) => {
    for (const item of menuList) {
        result[item.meta!.key!] = [...parent, item];
        if (item.children) getAllBreadcrumbList(item.children, result[item.meta!.key!], result);
    }
    return result;
}
export const formatMenuTree = (menuList: any) => {
    let newMenuList = JSON.parse(JSON.stringify(menuList));
    return newMenuList.filter((item: { children: string | any[]; meta: { hidden: boolean; }; }) => {
        item.children?.length && (item.children = formatMenuTree(item.children));
        return !item.meta?.hidden;
    });
};
export const getFlatMenuList = (menuList: any): Array<any> => {
    return menuList.flatMap((item: {
        children: any;
    }) => [item, ...(item.children ? getFlatMenuList(item.children) : [])]);
}

export const generateRouter = (menuList: Array<any>) => {
    const flatMenuList = JSON.parse(JSON.stringify(getFlatMenuList(menuList)))
    const newRoutes = flatMenuList.map((r: any) => {
        r.children && delete r.children;
        let route: Record<string, any> = {
            path: r.path,
            loader: () => {
                return {...r.meta, redirect: !!r.redirect};
            }
        }
        if (r.meta) route.meta = r.meta
        if (r.redirect) route.element = <Navigate to={r.redirect}/>;
        if (r.element) route.element =
            <RouterGuard>{LazyLoad(React.lazy(modules[`/src/views${r.element}.tsx`]))}</RouterGuard>
        return route
    })
    let dynamicRouter = [...staticRoutes, {element: <Layout/>, children: [...newRoutes]}]
    dynamicRouter.forEach((item: Record<string, any>) => item.path === "*" && (item.element = LazyLoad(React.lazy(() => import('@/components/Error/404/index.tsx')))))
    return dynamicRouter
};
